var express = require('express');
var router = express.Router();

var User = require("./../models/user")

/* GET users listing. */
router.get('/users', function (req, res, next) {
  res.send('respond with a resource');
});
//登陆
router.post("/login", function (req, res, next) {
  var param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  User.findOne(param, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (doc) {
        res.cookie('userName', doc.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        res.cookie('userId', doc.userId, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        // req.session.user = doc;
        res.json({
          status: '0',
          msg: '',
          result: {
            userName: doc.userName,
          }
        })
      }
    }
  })
})

//退出登陆
router.post("/logout", function (req, res, next) {
  res.cookie('userId', '', {
    path: '/',
    maxAge: -1,
  });
  res.json({
    status: '0',
    msg: '',
    result: '',
  })
})
//用户登陆状态
router.get("/checkedLogin", function (req, res, next) {
  if (req.cookies.userId) {
    res.json({
      status: '0',
      msg: '',
      result: req.cookies.userName || ''
    })
  } else {
    res.json({
      status: '1',
      msg: '木有登陆',
      result: ''
    })
  }
})

//购物车商品数量
router.get("/getCartCount",function (req,res,next) {
  if(req.cookies && req.cookies.userId){
      var userId = req.cookies.userId;
      User.findOne({userId:userId},function (err,doc) {
        if(err){
          res.json({
            status: '1',
            msg: err.message,
            result: '',
          })
        }else {
          var cartList = doc.cartList;
          var cartCount = 0;
          cartList.map(function (item) {
            cartCount+=parseInt(item.productNum)
          })
          res.json({
            status: '0',
            msg: '',
            result: cartCount,
          })
        }
      })
  }
})


//购物车列表
router.get('/cartList', function (req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({userId: userId}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (doc) {
        res.json({
          status: '0',
          msg: '',
          result: doc.cartList
        })
      }
    }
  })
})

//购物车删除
router.post('/cartDel', function (req, res, next) {
  var userId = req.cookies.userId, productId = req.body.productId;
  User.update({
    userId: userId
  }, {
    $pull: {
      'cartList': {
        'productId': productId
      }
    }
  }, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  });
})

//数量加减
router.post("/cartEdit", function (req, res, next) {
  var userId = req.cookies.userId,
    productId = req.body.productId,
    productNum = req.body.productNum,
    checked = req.body.checked;
  User.update({
    "userId": userId,
    "cartList.productId": productId
  }, {
    "cartList.$.productNum": productNum,
    "cartList.$.checked": checked,
  }, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  })
})

//购物车全选
router.post("/editCheckAll", function (req, res, next) {
  var userId = req.cookies.userId,
    checkAll = req.body.checkAll ? '1' : '0';
  User.findOne({userId: userId}, function (err, user) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (user) {
        user.cartList.forEach(function (item) {
          item.checked = checkAll
        })
        user.save(function (err1, doc) {
          if (err1) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '',
              result: 'success'
            })
          }
        })
      }
    }
  })
})

//获取用户地址接口
router.get('/addressList', function (req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({userId: userId}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: doc.addressList
      })
    }
  })
})


//设置默认地址
router.post("/setDefault", function (req, res, next) {
  var userId = req.cookies.userId,
    addressId = req.body.addressId;
  if (!addressId) {
    res.json({
      status: '1003',
      msg: 'addressId is null',
      result: ''
    })
  } else {
    User.findOne({userId: userId}, function (err, doc) {
      if (err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        var addressList = doc.addressList;
        addressList.forEach(function (item) {
          if (item.addressId == addressId) {
            item.isDefault = true
          } else {
            item.isDefault = false
          }
        });
        doc.save(function (err1, doc1) {
          if (err1) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '',
              result: ''
            })
          }
        })

      }
    })
  }

})


//删除地址接口
//$pull 删除子文档
router.post("/delAddress", function (req, res, next) {
  var userId = req.cookies.userId,
    addressId = req.body.addressId;
  User.update({
    userId: userId
  }, {
    $pull: {
      'addressList': {
        'addressId': addressId
      }
    }
  }, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      })
    }
  })
})


//生成订单
router.post("/payMent", function (req, res, next) {
  var userId = req.cookies.userId,
    addressId = req.cookies.addressId,
    orderTotal = req.body.orderTotal;
  User.findOne({userId: userId}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      var address = '', goodsList = [];
      //获取当前用户地址信息
      doc.addressList.forEach(function (item, index) {
        if (addressId == item.addressId) {
          address = item
        }
      })
      //获取用户购物车购买商品
      doc.cartList.filter(function (item, index) {
        if (item.checked == '1') {
          goodsList.push(item)
        }
      });

      //订单号生成
      var platform = '622';//平台码

      var r1 = Math.floor(Math.random() * 10);//0-9随机数
      var r2 = Math.floor(Math.random() * 10)

      var sysDtae = new Date().getTime();//日期 (16位)
      var createDate = new Date().getTime()//订单创建时间

      var orderId = platform + r1 + sysDtae + r2;//(21位订单id)
      var order = {
        orderId: orderId,
        orderTotal: orderTotal,
        addressInfo: address,
        goodsList: goodsList,
        orderStatus: '1',
        createDate: createDate
      }


      doc.orderList.push(order)
      doc.save(function (err1, doc1) {
        if (err1) {
          res.json({
            status: '1',
            msg: err.message,
            result: ''
          })
        } else {
          res.json({
            status: '0',
            msg: '',
            result: {
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      })
    }
  })
})


//根据订单id查询订单信息
router.get("/orderDetail",function (req,res,next) {
   var userId  =req.cookies.userId,
       orderId = req.param("orderId");
   User.findOne({userId:userId},function (err,userInfo) {
      if(err){
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      }else {
        var orderList = userInfo.orderList;
        if(orderList.length>0){
          var orderTotal = 0;
          orderList.forEach(function (item) {
             if(item.orderId =orderId ){
               orderTotal = item.orderTotal
             }
          });
          if(orderTotal>0){
            res.json({
              status: '0',
              msg: '',
              result: {
                orderId:orderId,
                orderTotal:orderTotal
              }
            })
          }else {
            res.json({
              status: '120001',
              msg: '么偶订单',
              result: ''
            })
          }

        }else {
          res.json({
            status: '120001',
            msg: '么偶订单',
            result: ''
          })
        }
      }
   })
})
module.exports = router;
